<template>
  <div class="distributor-form-modal" v-if="visible">
    <div class="modal-backdrop" @click="closeModal"></div>
    <div class="modal-container">
      <div class="modal-header">
        <h2 class="modal-title">{{ isEdit ? '编辑分销商' : '新增分销商' }}</h2>
        <button class="close-btn" @click="closeModal">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="handleSubmit" class="distributor-form">
          <!-- 分销商头像 -->
          <div class="avatar-upload">
            <div class="avatar-preview">
              <img :src="formData.avatar || defaultAvatar" alt="分销商头像" />
            </div>
            <div class="avatar-actions">
              <label for="avatar-upload" class="upload-btn">
                <i class="fas fa-upload"></i> 上传头像
              </label>
              <input 
                type="file" 
                id="avatar-upload" 
                accept="image/*" 
                @change="handleAvatarChange" 
                style="display: none;"
              >
            </div>
          </div>
          
          <!-- 基本信息 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            
            <div class="form-row">
              <div class="form-group">
                <label for="name">分销商名称 <span class="required">*</span></label>
                <input 
                  type="text" 
                  id="name" 
                  v-model="formData.name" 
                  :class="{ 'input-error': errors.name }"
                  placeholder="请输入分销商名称"
                >
                <span class="error-message" v-if="errors.name">{{ errors.name }}</span>
              </div>
              
              <div class="form-group">
                <label for="status">状态</label>
                <select id="status" v-model="formData.status">
                  <option value="active">活跃</option>
                  <option value="inactive">停用</option>
                  <option value="pending">待审核</option>
                </select>
              </div>
            </div>
          </div>
          
          <!-- 佣金信息 -->
          <div class="form-section">
            <h3 class="section-title">佣金信息</h3>
            
            <div class="form-group">
              <label for="commissionRate">佣金比例 ({{ formData.commissionRate }}%)</label>
              <div class="commission-slider">
                <input 
                  type="range" 
                  id="commissionRate" 
                  v-model.number="formData.commissionRate" 
                  :min="commissionLimits.min" 
                  :max="commissionLimits.max" 
                  step="0.5"
                  :class="{ 'input-error': errors.commissionRate }"
                >
                <div class="range-labels">
                  <span>{{ commissionLimits.min }}%</span>
                  <span>{{ commissionLimits.max }}%</span>
                </div>
              </div>
              <span class="error-message" v-if="errors.commissionRate">{{ errors.commissionRate }}</span>
              <span class="hint-text">此分销商可获得的销售佣金百分比</span>
            </div>
          </div>
          
          <!-- 备注信息 -->
          <div class="form-section">
            <h3 class="section-title">其他信息</h3>
            
            <div class="form-group full-width">
              <label for="remarks">备注信息</label>
              <textarea 
                id="remarks" 
                v-model="formData.remarks" 
                rows="3" 
                placeholder="请输入备注信息"
              ></textarea>
            </div>
          </div>
        </form>
      </div>
      
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
        <button type="button" class="btn btn-primary" @click="handleSubmit">保存</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, defineProps, defineEmits } from 'vue';

// 定义分销商接口
interface Distributor {
  id: string;
  name: string;
  avatar: string;
  commissionRate: number;
  status: 'active' | 'inactive' | 'pending';
  joinDate: string;
  remarks?: string;
  totalSales?: number;
  totalOrders?: number;
  totalCommission?: number;
}

// 定义Props
interface Props {
  visible: boolean;
  isEdit: boolean;
  distributor?: Partial<Distributor>;
  commissionLimits?: {
    min: number;
    max: number;
  }
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  isEdit: false,
  distributor: () => ({}),
  commissionLimits: () => ({ min: 5, max: 30 })
});

// 事件
const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void;
  (e: 'save', distributor: Partial<Distributor>): void;
}>();

// 默认头像
const defaultAvatar = 'https://randomuser.me/api/portraits/men/1.jpg';

// 表单数据
const formData = reactive<Partial<Distributor>>({
  name: '',
  avatar: '',
  commissionRate: 10,
  status: 'active',
  remarks: ''
});

// 表单验证错误
const errors = reactive<Record<string, string>>({});

// 监听props.distributor变化，更新formData
watch(() => props.distributor, (newValue) => {
  if (newValue) {
    Object.assign(formData, newValue);
  }
}, { immediate: true, deep: true });

// 验证表单
const validateForm = (): boolean => {
  errors.name = !formData.name ? '分销商名称不能为空' : '';
  
  // 佣金比例验证
  if (formData.commissionRate !== undefined) {
    if (formData.commissionRate < props.commissionLimits.min) {
      errors.commissionRate = `佣金比例不能低于${props.commissionLimits.min}%`;
    } else if (formData.commissionRate > props.commissionLimits.max) {
      errors.commissionRate = `佣金比例不能高于${props.commissionLimits.max}%`;
    } else {
      errors.commissionRate = '';
    }
  }
  
  // 检查是否有错误
  return !Object.values(errors).some(error => error);
};

// 关闭模态框
const closeModal = () => {
  emit('update:visible', false);
};

// 处理头像变更
const handleAvatarChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const reader = new FileReader();
    reader.onload = (e) => {
      formData.avatar = e.target?.result as string;
    };
    reader.readAsDataURL(input.files[0]);
  }
};

// 提交表单
const handleSubmit = () => {
  if (validateForm()) {
    emit('save', { ...formData });
    closeModal();
  }
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';
@import '@/assets/styles/mixins.scss';

.distributor-form-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: -1;
}

.modal-container {
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  animation: modalFadeIn 0.3s ease;
  overflow: hidden;
}

.modal-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e8eaed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .modal-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #1f2937;
  }
  
  .close-btn {
    background: transparent;
    border: none;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    cursor: pointer;
    color: #6b7280;
    transition: all 0.2s;
    
    &:hover {
      background-color: #f3f4f6;
      color: #1f2937;
    }
    
    i {
      font-size: 16px;
    }
  }
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
  max-height: calc(90vh - 130px);
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8eaed;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.distributor-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-section {
  padding-bottom: 20px;
  
  &:not(:last-child) {
    border-bottom: 1px solid #e8eaed;
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #1f2937;
    margin: 0 0 16px 0;
  }
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
  
  @media (max-width: 640px) {
    flex-direction: column;
    gap: 16px;
  }
}

.form-group {
  flex: 1;
  
  &.full-width {
    width: 100%;
  }
  
  label {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: #4b5563;
    margin-bottom: 6px;
    
    .required {
      color: #ef4444;
      margin-left: 4px;
    }
  }
  
  input, select, textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 14px;
    transition: all 0.2s;
    
    &:focus {
      border-color: #4f46e5;
      outline: none;
      box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }
    
    &.input-error {
      border-color: #ef4444;
      background-color: #fef2f2;
    }
  }
  
  select {
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20' stroke='%236b7280'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
    background-position: right 10px center;
    background-repeat: no-repeat;
    background-size: 20px;
    padding-right: 30px;
  }
  
  textarea {
    resize: vertical;
    min-height: 80px;
  }
  
  .error-message {
    color: #ef4444;
    font-size: 12px;
    margin-top: 4px;
    display: block;
  }
  
  .hint-text {
    color: #6b7280;
    font-size: 12px;
    margin-top: 4px;
    display: block;
  }
}

.commission-slider {
  input[type="range"] {
    width: 100%;
    -webkit-appearance: none;
    height: 6px;
    border-radius: 4px;
    background: #e5e7eb;
    outline: none;
    margin: 10px 0;
    
    &::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: #4f46e5;
      cursor: pointer;
      border: 2px solid #fff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    &::-moz-range-thumb {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: #4f46e5;
      cursor: pointer;
      border: 2px solid #fff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    &.input-error {
      background: #fecaca;
      
      &::-webkit-slider-thumb {
        background: #ef4444;
      }
      
      &::-moz-range-thumb {
        background: #ef4444;
      }
    }
  }
  
  .range-labels {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #6b7280;
  }
}

.avatar-upload {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-bottom: 20px;
  
  .avatar-preview {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;
    border: 2px solid #e5e7eb;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .avatar-actions {
    display: flex;
    flex-direction: column;
    gap: 8px;
    
    .upload-btn {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 8px 12px;
      background-color: #f3f4f6;
      border: 1px solid #d1d5db;
      border-radius: 6px;
      font-size: 14px;
      color: #4b5563;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background-color: #e5e7eb;
      }
      
      i {
        font-size: 14px;
      }
    }
  }
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 10px 16px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  
  &.btn-primary {
    background-color: #4f46e5;
    color: white;
    border: none;
    
    &:hover {
      background-color: #4338ca;
    }
  }
  
  &.btn-secondary {
    background-color: white;
    color: #4b5563;
    border: 1px solid #d1d5db;
    
    &:hover {
      background-color: #f3f4f6;
    }
  }
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 